//
//  AboutUsViewController.m
//  Choice
//
//  Created by A-01 on 2020/6/15.
//  Copyright © 2020 Mac. All rights reserved.
//

#import "AboutUsViewController.h"
#import "SendSuggestViewController.h"
#import "CallusViewController.h"

@interface AboutUsViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, weak)UITableView * tableView;
@property (nonatomic, strong)NSArray * titleArray;
@property (nonatomic, strong)NSArray * imgArray;

@end

@implementation AboutUsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"About us";
    self.view.backgroundColor = ZRWhiteColor;
    
    [self setupUI];
}

- (void)setupUI{
    
    UITableView * tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    tableView.backgroundColor = ZRWhiteColor;//ColorWithRGB(0xEFF0F1);
    tableView.rowHeight = 56;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    self.tableView = tableView;
    
    
    [self.view addSubview:self.tableView];
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        
//        SendSuggestViewController * suggestVC = [SendSuggestViewController new];
//
//        [self.navigationController pushViewController:suggestVC animated:YES];
        NSURLSession *session = [NSURLSession sharedSession];
        
        NSURL *url = [NSURL URLWithString:@"https://itunes.apple.com/CN/lookup?bundleId=com.LearningCalculator"];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            
            NSDictionary * dict = [self dictionaryForJsonData:data];
            NSArray *results = dict[@"results"];
            if(results.count > 0) {
                [self checkUpdateResult:results[0]];
            } else {
                [self showAlertWithType:1];
            }
        }];
        
        [task resume];
    }else{
        
        CallusViewController * callVC = [CallusViewController new];
        
        [self.navigationController pushViewController:callVC animated:YES];
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellID=@"cellID";
       UITableViewCell * cell=[tableView dequeueReusableCellWithIdentifier:cellID];
       if (cell==nil) {
           cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
       }
       cell.textLabel.text = self.titleArray[indexPath.row];
       cell.imageView.image = [UIImage imageNamed:self.imgArray[indexPath.row]];
    //cell右侧的小箭头
       cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
       return cell;
}


-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 280;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 280)];
    
    view.backgroundColor = ZRWhiteColor;
    
    
    UIImageView * toyImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60, 100, 100)];
    
    toyImageView.image = [UIImage imageNamed:@"toy"];
    toyImageView.centerX = view.centerX;
    
    [view addSubview:toyImageView];
    
    
    UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 180, kScreenW, 22)];
    
    titleLab.font = [UIFont boldSystemFontOfSize:16];
    titleLab.textColor = ZRBlackColor;
    titleLab.text = @"Best Choice";
    titleLab.textAlignment = NSTextAlignmentCenter;
    
    [view addSubview:titleLab];
    
    
    UILabel * versionLab = [[UILabel alloc] initWithFrame:CGRectMake(0, 220, kScreenW, 17)];
    
    versionLab.font = [UIFont systemFontOfSize:12];
    versionLab.textColor = [UIColor colorWithHexString:@"BABABA"];
    NSString * version = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
    versionLab.text = [NSString stringWithFormat:@"version %@",version];
    versionLab.textAlignment = NSTextAlignmentCenter;
    
    [view addSubview:versionLab];
    
    return view;
}

#pragma mark-- 版本更新
- (void)checkUpdateResult:(NSDictionary *)response {
    
    NSString * localVersion = [[NSBundle mainBundle].infoDictionary objectForKey:@"CFBundleShortVersionString"];
    //对比手机里的版本和App Store上的版本号，如果App Store上的大于当前系统的，就继续执行代码
    if(response &&
       ([response[@"version"] compare:localVersion] == NSOrderedDescending)) {
        //有新版本
        [self showAlertWithType:2];
    } else {
        //当前是最新
        [self showAlertWithType:1];
    }
}

- (void)showAlertWithType:(NSInteger)type{
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (type == 1) {
            //最新版本
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:@"已经是最新版本了"
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"暂不更新" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {

                                                                  }];

            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"版本更新"
                                                                           message:@"快去更新吧！"
                                                                    preferredStyle:UIAlertControllerStyleAlert];

            UIAlertAction* sureAction = [UIAlertAction actionWithTitle:@"立即更新" style:UIAlertActionStyleDefault
                                                                  handler:^(UIAlertAction * action) {
                
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/us/app/id1538756118"]];
                
                                                                  }];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"暂不更新" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {

                                                                  }];

            [alert addAction:sureAction];
            [alert addAction:cancelAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}


-(NSDictionary *)dictionaryForJsonData:(NSData *)jsonData{

    if (![jsonData isKindOfClass:[NSData class]] || jsonData.length < 1) {

        return nil;
    }

    id jsonObj = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

    if (![jsonObj isKindOfClass:[NSDictionary class]]) {

        return nil;
    }

    return [NSDictionary dictionaryWithDictionary:(NSDictionary *)jsonObj];
}

- (NSArray *)titleArray{
    
    if (!_titleArray) {
        
        _titleArray = @[@"Version Updating",@"Contact"];
    }
    
    return _titleArray;
}

- (NSArray *)imgArray{
    
    if (!_imgArray) {
        
        _imgArray = @[@"feedback",@"function"];
    }
    
    return _imgArray;
}

@end
